﻿using mozhi.smarterp.BasicData.TaxRates.Repository;
using mozhi.smarterp.BasicData.Units;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Services;

namespace mozhi.smarterp.BasicData.TaxRates.Service
{
    public class TaxRateManager : DomainService
    {
        private ITaxRateRepository _repository;

        public TaxRateManager(ITaxRateRepository repository)
        {
            _repository = repository;
        }

        public async Task<TaxRate> CreateAsync(Guid id, string code, string name, decimal rate, bool activated)
        {
            var matchCount = await _repository.GetCountAsync(code, null, null) + await _repository.GetCountAsync(null, name, null);

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            var taxrate = new TaxRate(id, code, name, rate, activated);

            return taxrate;
        }

        public async Task<TaxRate> UpdateAsync(Guid id, string code, string name, decimal rate, bool activated)
        {
            var taxrate = await _repository.GetAsync(id);

            if (taxrate == null)
                throw new BusinessException($"税率：{id}不存在", "100000");

            var matchCount = await _repository.GetCountAsync(code, null, id) + await _repository.GetCountAsync(null, name, id);

            if (matchCount > 0)
                throw new UserFriendlyException("编码或者名称已经存在", "100000");

            taxrate.Change(code, name, activated);

            return taxrate;
        }
    }
}
